﻿using DeliveryManage.Models;
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Helpers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Security;

namespace DeliveryManage.Filter
{
    public class TokenCheckFilter : AuthorizeAttribute
    {
        /// <summary>
        /// 重写基类的验证方式，加入自定义的Ticket验证
        /// </summary>
        /// <param name="actionContext"></param>
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            var content = actionContext.Request.Properties["MS_HttpContext"] as HttpContextBase;
            //获取token（请求头里面的值）
            var token = HttpContext.Current.Request.Headers["Token"] ?? "";
            //是否为空或
            if (!string.IsNullOrEmpty(token.ToString()))
            {
                //解密用户ticket,并校验用户名密码是否匹配
                if (ValidateUserTicket(token.ToString()))
                    base.IsAuthorized(actionContext);
                else
                    HandleUnauthorizedRequest(actionContext);
            }
            //如果取不到身份验证信息，并且不允许匿名访问，则返回未验证404
            else
            {
                var attributes = actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().OfType<AllowAnonymousAttribute>();
                bool isAnonymous = attributes.Any(a => a is AllowAnonymousAttribute);
                if (isAnonymous) base.OnAuthorization(actionContext);
                else HandleUnauthorizedRequest(actionContext);
            }
        }
        
        /// <summary>
        /// 校验用户ticket信息
        /// </summary>
        /// <param name="encryptTicket"></param>
        /// <returns></returns>
        private bool ValidateUserTicket(string encryptTicket)
        {
            var userTicket = FormsAuthentication.Decrypt(encryptTicket);
            var userTicketData = userTicket.UserData;
            if (userTicket.Expired) {
                return false;
            }
            string userName = userTicketData.Substring(0, userTicketData.IndexOf(":"));
            string password = userTicketData.Substring(userTicketData.IndexOf(":") + 1);
            
            //检查用户是否被冻结，冻结直接返回
            DeliveryManage.DAL.Sys_User dal = new DeliveryManage.DAL.Sys_User();
            //把明文进行加密重新赋值
            DeliveryManage.Model.Sys_User model = dal.GetModel(userName, password);
            bool isQuilified = false;
            if (model != null && model.Status == true)
            {
                isQuilified = true;
            }
            return isQuilified;
        }

        /// <summary>
        /// 重写HandleUnauthorizedRequest
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void HandleUnauthorizedRequest(HttpActionContext filterContext)
        {
            base.HandleUnauthorizedRequest(filterContext);

            var response = filterContext.Response = filterContext.Response ?? new HttpResponseMessage();
            //状态码401改为其他状态码来避免被重定向。表示服务器拒绝。
            response.StatusCode = HttpStatusCode.Forbidden;
            var content = new
            {
                status = false,
                code=404,
                msg= "Login expired,please login again!",
                data = ""
            };
            response.Content = new StringContent(Json.Encode(content), Encoding.UTF8, "application/json");
        }
    }
}